import { DefaultLayout } from "@/layout";
import { useAuthStore } from "@/store";
import type { MessageData } from "@/types";
import { eventBus } from "@/utils";
import { Message, Notification } from "@arco-design/web-react";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import {
	Navigate,
	Outlet,
	createRootRoute,
	useLocation,
} from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import { useEffect } from "react";

export const Route = createRootRoute({
	component: function Root() {
		const { isAuthenticated } = useAuthStore();

		const location = useLocation();
		const isLogin = location.pathname === "/login";

		useEffect(() => {
			eventBus.subscribe<MessageData>("message", (data) => {
				if (!data.content) return;

				switch (data.type) {
					case "message":
						Message[data.level](data.content);
						break;
					case "notification":
						Notification[data.level]({
							content: data.content,
						});
						break;
					default:
						break;
				}
			});

			return () => {
				eventBus.unsubscribe("message");
			};
		}, []);

		return (
			<>
				{isLogin ? (
					<Outlet />
				) : isAuthenticated ? (
					<DefaultLayout />
				) : (
					<Navigate to="/login" search={{ returnUrl: location.href }} replace />
				)}
				<TanStackRouterDevtools position="top-right" />
				<ReactQueryDevtools buttonPosition="bottom-right" />
			</>
		);
	},
});
